<?php
namespace app\admin\service;

use app\admin\model\Memb;
use app\admin\model\Sport;
use app\admin\model\SportDel;
use app\admin\model\Annual;
use app\admin\model\User;
use app\admin\model\Match;
use app\admin\model\Project;

class SportService extends BaseService
{
    protected $annualModel = "";
    public function __construct()
    {
        $this->model = new Sport();
        $this->annualModel = new Annual();
    }

    public function getList($uid = '')
    {
        $param = request()->param();

        // 初始化变量
        $map = [];
        $sort = 'createdDate desc';
        $is_sql = 0;

        // 获取参数
       /* $argList = func_get_args();
        if (!empty($argList)) {
            // 查询条件
            $map = (isset($argList[0]) && !empty($argList[0])) ? $argList[0] : [];
            // 排序
            $sort = (isset($argList[1]) && !empty($argList[1])) ? $argList[1] : 'id desc';
            // 是否打印SQL
            $is_sql = isset($argList[2]) ? isset($argList[2]) : 0;
        }*/

        $user = User::get($uid);
        if($user && $user['user_type'] == '2'){
            $memb = Memb::where('roll',$user['username'])->cache(500)->find();
            //$memberId = $memb?$memb['id']:0;
            $memberId = 0;
            if($memb){
                $memberId = $memb['id'];
            }
            $map[] = ['memberId','=',$memberId];
        }elseif($user && $user['id']!=1 && $user['user_type'] == '1'){
            if ($user['departmentsId']) {
                $map[] = ['departmentsId','=',$user['departmentsId']];
            }
            
        }

        // 常规查询条件
        $param = request()->param();
        if ($param) {

            if (isset($param['sort']) && $param['sort']) {
                $sort = $param['sort']." ".$param["order"];
            }
			if(isset( $param['type']) && $param['type'] == 2 && getParamStr('username')){
				$map[] = ['testerName|testerNumber', 'like', "%{$param['username']}%"];
			}else{
				// 筛选名称
				if (getParamStr('username')) {
					$map[] = ['testerName', 'like', "%{$param['username']}%"];
				}
			}
            
			
            if (isset($param['type']) && $param['type']) {
                $map[] = ['type', '=', $param['type']];
            }
            // 筛选标题
            if (getParamStr('title')) {
                $map[] = ['title', 'like', "%{$param['title']}%"];
            }

            // 项目
            $projectId = getParamInt('projectId') ? (int)$param['projectId'] : 0;
            if ($projectId) {
                if($projectId == 39){
                    $map[] = ['itemCode', 'in', ['weight','height']];
                }else{
                    $map[] = ['projectId', '=', $projectId];
                }
            }
            if (!empty($param['projectCodes'])) {
                if (in_array('BMI', $param['projectCodes'])) {
                    $param['projectCodes'][] = 'weight';
                    $param['projectCodes'][] = 'height';
                }
                $projectIds = (new Project)->whereIn('code', $param['projectCodes'])->column('id');
                $map[] = ['projectId', 'in', $projectIds];
            }

            $keywords = getParamStr('keywords') ? (string)$param['keywords'] : '';
            if ($keywords) {
                $map[] = ['testerName|testerNumber', 'like', "%{$keywords}%"];
            }

            // 学年
            if (getParamInt('gradeId')) {
                $map[] = ['gradeId', '=', $param['gradeId']];
            }

            // 院系
            if (getParamInt('departmentsId')) {
                $map[] = [getDepartField($param['departmentsId']), '=', $param['departmentsId']];
            }

            // 专业
            if (getParamInt('professionalId')) {
                if(isset($param['departmentsId']) && $param['departmentsId']){
                    $map[] = [getProfField($param['departmentsId']), '=', $param['professionalId']];
                }else{
                    $map[] = ['professionalId', '=', $param['professionalId']];
                }

            }

            // 班级
            if (getParamInt('classId')) {
                if(isset($param['departmentsId']) && $param['departmentsId']){
                    $map[] = [getClassField($param['departmentsId']), '=', $param['classId']];
                }else{
                    $map[] = ['classId', '=', $param['classId']];
                }
            }

            // 性别
            if (getParamInt('gender')) {
                $map[] = ['gender', '=', $param['gender']];
            }
            if(getParamInt('taskId')){
                $map[] = ['taskId', '=', $param['taskId']];
            }
            if (getParamInt('annual')) {
                $annualResult = $this->annualModel->getInfo($param['annual']);
                $starttime = isset($annualResult['xue_start']) ? trim($annualResult['xue_start']) : '';
                $endtime = isset($annualResult['xue_end']) ? trim($annualResult['xue_end']) : '';
                if ($starttime&&$endtime) {
                    $map[] = ['createdDate', ['>= time', $starttime],['<= time', $endtime]];
                }
            }
            
            
            
            // 时间
            $starttime = getParamStr('startTime');
            $endtime = getParamStr('endTime');
            if ($starttime&&$endtime) {
                $map[] = ['createdDate', '>= time', $starttime];
                $map[] = ['createdDate', '<= time', $endtime.' 23:59:59'];
            }
        }
        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }

        $result = $this->model->where($map)->field('id')
            //->cache(true,7200)
            ->order($sort)->page(PAGE, PERPAGE)
            ->column("id");

        // echo $this->model->getLastSql();

        // 打印SQL
        if ($is_sql) {
            echo $this->model->getLastSql();
        }

        $list = [];
        if (is_array($result)) {
            foreach ($result as $val) {
                $info = $this->model->getInfo2($val,$uid);
                $list[] = $info;
            }
        }

        //获取数据总数
        $count = $this->model->where($map)
            //->cache(true,7200)
            ->count();

        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        return $message;
    }

    public function getRankList($uid = '')
    {
        $param = request()->param();

        // 初始化变量
        $map = [];
        $map2 = [];
        $sort = 'pingscore desc';
        $is_sql = 0;
        $ds = 'pingscore desc';
        $fs = '';
        $user = User::get($uid);
        if($user && $user['user_type'] == '2'){
            $memb = Memb::where('roll',$user['username'])->find();
            //$memberId = $memb?$memb['id']:0;
            $memberId = 0;
            if($memb){
                $memberId = $memb['id'];
            }
            $map2[] = ['memberId','=',$memberId];
        }

        // 常规查询条件
        $param = request()->param();
        if ($param) {
            $match = new Match();
            // if (isset($param['sort']) && $param['sort']) {
            //     $sort = $param['sort']." ".$param["order"];
            // }

            // 筛选名称
            if (isset($param['username']) && $param['username']) {
                $map[] = ['testerName', 'like', "%{$param['username']}%"];
            }
            if (isset($param['type']) && $param['type']) {
                $map[] = ['type', '=', $param['type']];
            }
            // 筛选标题
            if (isset($param['title']) && $param['title']) {
                $map[] = ['title', 'like', "%{$param['title']}%"];
            }

            // 项目
            if (isset($param['projectId']) && $param['projectId']) {
                $map[] = ['projectId', '=', $param['projectId']];
            }

            // 学年
            if (isset($param['gradeId']) && $param['gradeId']) {
                $map[] = ['gradeId', '=', $param['gradeId']];
            }

            // 院系
            if (isset($param['departmentsId']) && $param['departmentsId']) {
                $map[] = ['departmentsId', '=', $param['departmentsId']];
            }

            // 专业
            if (isset($param['professionalId']) && $param['professionalId']) {
                $map[] = ['professionalId', '=', $param['professionalId']];
            }

            // 班级
            if (isset($param['classId']) && $param['classId']) {
                $map[] = ['classId', '=', $param['classId']];
            }

            // 性别
            if (isset($param['gender']) && $param['gender']) {
                $map[] = ['gender', '=', $param['gender']];
            }
            if(isset($param['taskId']) && (int)$param['taskId']){
                $taskId = $param['taskId'];
                $matchdata = [];
                if ($taskId) {
                    $ds = 'score desc,pingscore desc';
                    $fs = 'id,memberId,MAX(score) as score,pingscore';
                    $map[] = ['taskId', '=', $taskId];
                    // $tiyuclass = json_decode(Match::where('id',$taskId)->value('class'),true);
                    // $map[] = ['tiyu_class', '=', intval($tiyuclass[0])];

                    $project = Match::where('id',$taskId)->value('projectId');
                    $code = Project::where('id',$project)->value('code');

                    $btype = Project::where('id',$project)->value('btype');
                    if ($btype==2) {
                        $ds = 'pingscore desc,score asc';
                        $fs = 'id,memberId,MIN(score) as score,pingscore';
                    }
                    if ($code=='BMI') {
                        $map[] = ['bmi', '<>', ''];
                        $ds = 'pingscore desc,bmi asc';
                    }
                    $matchdata = $match->where(['id'=>$taskId,'mark'=>1])->find();
                    if ($matchdata&&$matchdata['gradeId']) {
                        $map[] = ['gradeId', '=', $matchdata['gradeId']];
                    }
                    if ($matchdata&&$matchdata['departmentsId']) {
                        $map[] = ['departmentsId', '=', $matchdata['departmentsId']];
                    }
                }

        
            }
            if (isset($param['annual']) && $param['annual']) {
                
                $annualResult = $this->annualModel->getInfo($param['annual']);
                $starttime = isset($annualResult['xue_start']) ? trim($annualResult['xue_start']) : '';
                $endtime = isset($annualResult['xue_end']) ? trim($annualResult['xue_end']) : '';
                if ($starttime&&$endtime) {
                    $map[] = ['createdDate', '>= time', $starttime];
                    $map[] = ['createdDate', '<= time', $endtime];
                }
            }
            
            
            
            // 时间
            $starttime = isset($param['starttime']) ? trim($param['starttime']) : '';
            $endtime = isset($param['endtime']) ? trim($param['endtime']) : '';
            if ($starttime&&$endtime) {
                $map[] = ['createdDate', '>= time', $starttime];
                $map[] = ['createdDate', '<= time', $endtime];
            }
        }
        // 排序
        $sort = isset($param['sort']) && $param['order'] ? $param['sort'] . ' ' . $param['order'] : $ds;
        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }
        
        $result = $this->model->where($map)->where($map2)->order($sort)->group('memberId')->page(PAGE, PERPAGE)->field($fs)->column("id");

        $uids = $this->model->where($map)->order($sort)->group('memberId')->column("memberId");

        // echo $this->model->getLastSql();

        // 打印SQL
        if ($is_sql) {
            echo $this->model->getLastSql();
        }

        $list = [];
        if (is_array($result)) {
            $d = ((PAGE-1)*PERPAGE)+1;
            
            foreach ($result as $val) {
                $info = $this->model->getrankInfo($val);
                $info['rank'] = $d;
                if($user && $user['user_type'] == '2'){
                    $info['rank'] = array_search($info['memberId'], $uids)+1;
                }
                $list[] = $info;
                $d++;
            }
        }

        //获取数据总数
        $count = $this->model->where($map)->where($map2)->group('memberId')->count();

        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        return $message;
    }


     public function getdelList($uid = '')
    {
        $user = new User();
        $userInfo = $user->getInfo($uid);
        if ($userInfo['ish5']!=1&&$userInfo['user_type']==2) {
            return $this->jsonReturn(message("权限不足", false));
        }
        $param = request()->param();

        // 初始化变量
        $map = [];
        $sort = 'id desc';
        $is_sql = 0;

        // 获取参数
       /* $argList = func_get_args();
        if (!empty($argList)) {
            // 查询条件
            $map = (isset($argList[0]) && !empty($argList[0])) ? $argList[0] : [];
            // 排序
            $sort = (isset($argList[1]) && !empty($argList[1])) ? $argList[1] : 'id desc';
            // 是否打印SQL
            $is_sql = isset($argList[2]) ? isset($argList[2]) : 0;
        }*/

        // 常规查询条件
        $param = request()->param();
        if ($param) {

            if (isset($param['sort']) && $param['sort']) {
                $sort = $param['sort']." ".$param["order"];
            }

            // 筛选名称
            if (getParamStr('username')) {
                $map[] = ['testerName', 'like', "%{$param['username']}%"];
            }
            if (isset($param['type']) && $param['type']) {
                $map[] = ['type', '=', $param['type']];
            }
            // 筛选标题
            if (getParamStr('title')) {
                $map[] = ['title', 'like', "%{$param['title']}%"];
            }

            // 项目
            $projectId = getParamInt('projectId') ? (int)$param['projectId'] : 0;
            if ($projectId) {
                if($projectId == 39){
                    $map[] = ['itemCode', 'in', ['weight','height']];
                }else{
                    $map[] = ['projectId', '=', $projectId];
                }
            }

            $keywords = getParamStr('keywords') ? (string)$param['keywords'] : '';
            if ($keywords) {
                $map[] = ['testerName|testerNumber', 'like', "%{$keywords}%"];
            }

            // 学年
            if (getParamInt('gradeId')) {
                $map[] = ['gradeId', '=', $param['gradeId']];
            }

            // 院系
            if (getParamInt('departmentsId')) {
                $map[] = [getDepartField($param['departmentsId']), '=', $param['departmentsId']];
            }

            // 专业
            if (getParamInt('professionalId')) {
                if(isset($param['departmentsId']) && $param['departmentsId']){
                    $map[] = [getProfField($param['departmentsId']), '=', $param['professionalId']];
                }else{
                    $map[] = ['professionalId', '=', $param['professionalId']];
                }

            }

            // 班级
            if (getParamInt('classId')) {
                if(isset($param['departmentsId']) && $param['departmentsId']){
                    $map[] = [getClassField($param['departmentsId']), '=', $param['classId']];
                }else{
                    $map[] = ['classId', '=', $param['classId']];
                }
            }

            // 性别
            if (getParamInt('gender')) {
                $map[] = ['gender', '=', $param['gender']];
            }
            if(getParamInt('taskId')){
                $map[] = ['taskId', '=', $param['taskId']];
            }
            if (getParamInt('annual')) {
                $annualResult = $this->annualModel->getInfo($param['annual']);
                $starttime = isset($annualResult['xue_start']) ? trim($annualResult['xue_start']) : '';
                $endtime = isset($annualResult['xue_end']) ? trim($annualResult['xue_end']) : '';
                if ($starttime&&$endtime) {
                    $map[] = ['createdDate', ['>= time', $starttime],['<= time', $endtime]];
                }
            }
            
            
            
            // 时间
            $starttime = getParamStr('startTime');
            $endtime = getParamStr('endTime');
            if ($starttime&&$endtime) {
                $map[] = ['createdDate', '>= time', $starttime];
                $map[] = ['createdDate', '<= time', $endtime.' 23:59:59'];
            }
        }
        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }
        
        $result = $this->model->where($map)->order($sort)->page(PAGE, PERPAGE)->column("id");

        // echo $this->model->getLastSql();

        // 打印SQL
        if ($is_sql) {
            echo $this->model->getLastSql();
        }

        $list = [];
        if (is_array($result)) {
            foreach ($result as $val) {
                $info = $this->model->getInfo($val);
                $list[] = $info;
            }
        }

        //获取数据总数
        $count = $this->model->where($map)->count();

        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        return $message;
    }


    public function getdelrecoverList($uid = '')
    {
        $sportdel = new SportDel();
        $param = request()->param();

        // 初始化变量
        $map = [];
        $sort = 'deletetime desc';
        $is_sql = 0;

        // 常规查询条件
        $param = request()->param();
        if ($param) {

            if (isset($param['sort']) && $param['sort']) {
                $sort = $param['sort']." ".$param["order"];
            }

            
            // 项目
            $projectId = getParamInt('projectId') ? (int)$param['projectId'] : 0;
            if ($projectId) {
                if($projectId == 39){
                    $map[] = ['itemCode', 'in', ['weight','height']];
                }else{
                    $map[] = ['projectId', '=', $projectId];
                }
            }

            $keywords = getParamStr('keywords') ? (string)$param['keywords'] : '';
            if ($keywords) {
                $map[] = ['testerName|testerNumber', 'like', "%{$keywords}%"];
            }

            // 学年
            if (getParamInt('gradeId')) {
                $map[] = ['gradeId', '=', $param['gradeId']];
            }

            // 院系
            if (getParamInt('departmentsId')) {
                $map[] = [getDepartField($param['departmentsId']), '=', $param['departmentsId']];
            }

            // 专业
            if (getParamInt('professionalId')) {
                if(isset($param['departmentsId']) && $param['departmentsId']){
                    $map[] = [getProfField($param['departmentsId']), '=', $param['professionalId']];
                }else{
                    $map[] = ['professionalId', '=', $param['professionalId']];
                }

            }

            // 班级
            if (getParamInt('classId')) {
                if(isset($param['departmentsId']) && $param['departmentsId']){
                    $map[] = [getClassField($param['departmentsId']), '=', $param['classId']];
                }else{
                    $map[] = ['classId', '=', $param['classId']];
                }
            }

            // 性别
            if (getParamInt('gender')) {
                $map[] = ['gender', '=', $param['gender']];
            }
            if(getParamInt('taskId')){
                $map[] = ['taskId', '=', $param['taskId']];
            }
            if (getParamInt('annual')) {
                $annualResult = $this->annualModel->getInfo($param['annual']);
                $starttime = isset($annualResult['xue_start']) ? trim($annualResult['xue_start']) : '';
                $endtime = isset($annualResult['xue_end']) ? trim($annualResult['xue_end']) : '';
                if ($starttime&&$endtime) {
                    $map[] = ['createdDate', ['>= time', $starttime],['<= time', $endtime]];
                }
            }
            
            
            
            // 日期区间查询
            $startEndTime = isset($param['start_end']) ? $param['start_end'] : [];
            if ($startEndTime && is_array($startEndTime)) {
                // 时间区间查询
                $map[] = ['createdDate', 'between time', [$startEndTime[0], $startEndTime[1].' 23:59:59']];
            }

            // 日期区间查询
            $startEndTime2 = isset($param['start_end2']) ? $param['start_end2'] : [];
            if ($startEndTime2 && is_array($startEndTime2)) {
                // 时间区间查询
                $map[] = ['deletetime', 'between time', [$startEndTime2[0], $startEndTime2[1].' 23:59:59']];
            }
        }
        // 设置查询条件
        // if (is_array($map)) {
        //     $map[] = ['mark', '=', 1];
        // } elseif ($map) {
        //     $map .= " AND mark=1 ";
        // } else {
        //     $map .= " mark=1 ";
        // }
         $map[] = ['memberId', '<>', ''];
        $result = $sportdel->where($map)->order($sort)->page(PAGE, PERPAGE)->column("tbid");

        // echo $this->model->getLastSql();

        // 打印SQL
        if ($is_sql) {
            echo $sportdel->getLastSql();
        }

        $list = [];
        if (is_array($result)) {
            foreach ($result as $val) {
                $info = $sportdel->getInfo($val);
                $list[] = $info;
            }
        }

        //获取数据总数
        $count = $sportdel->where($map)->count();

        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        return $message;
    }

    public function standardCalc($standard, $value, $gender): array
    {
        if (!$standard) {
            return ['', ''];
        }
        $rating   = '';
        $score    = '';
        $standard = json_decode($standard, true);
        foreach ($standard as $vv) {
            if ($vv['sex'] != $gender) {
                continue;
            }
            switch ($vv['conditions']) {//判断成绩评级
                case 'gt':
                    if ($value > $vv['target'][0]) {
                        $rating = $vv['level'];
                        $score  = $vv['score'];
                    }
                    break;
                case 'egt':
                    if ($value >= $vv['target'][0]) {
                        $rating = $vv['level'];
                        $score  = $vv['score'];
                    }
                    break;
                case 'lt':
                    if ($value < $vv['target'][0]) {
                        $rating = $vv['level'];
                        $score  = $vv['score'];
                    }
                    break;
                case 'elt':
                    if ($value <= $vv['target'][0]) {
                        $rating = $vv['level'];
                        $score  = $vv['score'];
                    }
                    break;
                case 'between':
                    if ($value >= $vv['target'][0] && $value <= $vv['target'][1]) {
                        $rating = $vv['level'];
                        $score  = $vv['score'];
                    }
                    break;
                default:
                    break;
            }
        }

        return [$rating, $score];
    }
}